package com.jiubanqingchen.wish.interceptors;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jiubanqingchen.wish.framework.base.controller.BaseController;
import com.jiubanqingchen.wish.framework.consts.BaseKey;
import com.jiubanqingchen.wish.framework.enums.SystemStatus;
import com.jiubanqingchen.wish.framework.support.JwtSupport;
import com.jiubanqingchen.wish.org.online.OnlineUser;
import com.jiubanqingchen.wish.org.online.OnlineUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author light_dust
 * @since 2020/12/28 17:34
 */
public class LoginInterceptor implements Interceptor {
    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();
        HttpServletRequest request = controller.getRequest();
        String token = request.getHeader(BaseKey.TOKEN_KEY);// 得到当前token
        String userId = JwtSupport.me().verifyToken(token);
        //获取当前在线用户信息
        OnlineUser onlineUser = Aop.get(OnlineUserService.class).getOnLineUser(userId);
        if (onlineUser == null || !onlineUser.getTokenList().contains(token)) {
            controller.renderJson(SystemStatus.LOGOUT);
        } else {
            controller.setSessionAttr(BaseKey.CURRENT_TOKEN, token);//设置当前用户token
            controller.setSessionAttr(BaseKey.CURRENT_USER_ID_KEY, userId);//设置当前用户id
            inv.invoke();
        }
    }
}
